import {Link} from 'react-router-dom';
import {Select, Alert, Input, Modal, Form, Row, Col, Table, Breadcrumb, Icon,Upload ,Button,DatePicker} from 'antd';

const Option = Select.Option;
const FormItem = Form.Item;
import AppService from './../../common/utils/app.service'
import * as Actions from './action'
import Utils from './../../common/utils/utils'
import * as CONSTANTS from './../../common/utils/constants'
import UploadImage from "./../../common/utils/app.service";
import axios from 'axios'
var Delta = require('quill-delta/lib/delta');
import ReactQuill, {Quill, Mixin, Toolbar} from 'react-quill'
import Moment from 'moment'

const modules = {
    toolbar: {
        container: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],

            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
            [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
            // [{ 'direction': 'rtl' }],                         // text direction

            [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
            [{'header': [1, 2, 3, 4, 5, 6]}],

            [{'color': []}, {'background': []}],          // dropdown with defaults from theme
            [{'font': []}],
            [{'align': []}],
            ['link', 'image'],
            // ['video'],
            ['clean']
        ],
        handlers: {
            "image": function () {
                let fileInput = this.container.querySelector('input.ql-image[type=file]');
                if (fileInput == null) {
                    fileInput = document.createElement('input');
                    fileInput.setAttribute('type', 'file');
                    fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
                    fileInput.classList.add('ql-image');
                    fileInput.addEventListener('change', () => {
                        if (fileInput.files != null && fileInput.files[0] != null) {
                            var formData = new FormData();
                            formData.append("upfile", fileInput.files[0]);
                            formData.append("withStatus", true);
                            axios.post(UploadImage.uploadImgUrl, formData, {
                                headers: {
                                    'Content-Type': 'multipart/form-data'
                                },
                                responseType: 'json'
                            }).then(res => {
                                if (res.data.errorCode == 0) {
                                    let range = this.quill.getSelection(true);
                                    this.quill.updateContents(new Delta()
                                        .retain(range.index)
                                        .delete(range.length)
                                        .insert({image: res.data.body})
                                        , Quill.sources.USER);
                                } else {
                                    console.error(res.data);
                                }
                            }).catch(e => {
                                console.error(e);
                            });
                        }
                    });
                    this.container.appendChild(fileInput);
                }
                fileInput.click();
            }
        }
    }
}

class BaseSettingDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detail:{},
        fileList: [],
        previewVisible: false,
        id:1
    }
  }


  componentDidMount() {
    let _this = this, {dispatch, match} = this.props;
       _this.getDateils();
    console.log('detail',this.props);
  }

  getDateils = () => {
      let _this = this;
    Actions.getBaseSettingDetail().then(response => {
      if (response.errorCode === 0) {

          this.setState({
            detail:response.body,
              id:response.body.id
        })
      }
    })
  };


    handleSubmit = (e) => {
        e.preventDefault();
        let _this = this , { history} = this.props;


        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                _this.setState({buttonLoading: true})
                let params = values;
                 _this.updateBase(params)
            }
        });
    }



    updateBase = (params)=>{
        let _this = this , {history, match} = this.props;
        let id = this.state.id;
        Actions.updateBaseSetting(id,params).then((res)=>{
            console.log(res);
            _this.setState({buttonLoading: false})

            Utils.dialog.success('更新成功',()=>{
                history.push('/admin/basesetting/index')
            });

        })
    }



    onChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    }

    // 上传图片之前
    beforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isLt2M) {
            Utils.dialog.error('图片大小不能超过2MB!');
        }
        return isLt2M;
    }

    // 图片改变
    shandleChange = (prop, {file, fileList}) => {
        if (file.response && file.response.errorCode === 0) {
            let detail = this.state.detail
            detail[prop] = file.response.body
            this.setState({detail})
        } else if (file.response && file.response.errorCode != 0) {
            Utils.dialog.error(file.response.msg)
        }
    }

    // 上传图片时，转换返回的数据
    normFile = (e) => {
        let fileList = e.fileList.filter((file) => {
            if (file.response) {
                if (file.response.errorCode === 0) {
                    file.url = file.response.body
                    return true;
                }
            }
            return true;
        }).slice(-1);
        return fileList[0].url;
    }





  // 富文本编辑器内容改变
  handleEditorChange = (value) => {
    this.setState({
      content: value
    })
  }


  render() {
    const {match} = this.props;
       const { getFieldDecorator } = this.props.form;
    const {detail ,fileList,previewVisible, previewImage} = this.state
      const uploadButton = (
          <div>
              <Icon type="plus" />
              <div className="ant-upload-text">Upload</div>
          </div>
      );
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 6},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
      },
    };
      const tailFormItemLayout = {
          wrapperCol: {
              xs: {
                  span: 24,
                  offset: 0,
              },
              sm: {
                  span: 14,
                  offset: 6,
              },
          },
      };

      const props = {
          className: "avatar-uploader",
          action: `${UploadImage.uploadImgUrl}`,
          showUploadList: false,
          withCredentials: true,
          beforeUpload: this.beforeUpload.bind(this),
          onChange: this.shandleChange.bind(this, 'welcomeBg'),
          name: 'upfile',
          accept: "image/*",
          data: {
              withStatus: true
          },
          headers: {
              'X-Requested-With': null,
          },
          onProgress: null,
      };







    return (
      <div id="wrap">
        <Breadcrumb className="breadcrumb">

          <Breadcrumb.Item>
              小程序配置
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="content">


            <Form onSubmit={this.handleSubmit}>

                <FormItem
                    {...formItemLayout}
                    label='启动页图片'
                    hasFeedback
                >
                    {getFieldDecorator('welcomeBg', {
                        rules: [{ required: true, message: '请上传一张图片' }],
                        getValueFromEvent: this.normFile.bind(this),
                        initialValue:location.hash.indexOf('add') > 0 ? undefined : detail.welcomeBg
                    })(

                        <Upload
                            {...props}
                        >
                            {
                                detail.welcomeBg ?
                                    <img src={detail.welcomeBg} alt="" className="avatar "/> :
                                    <Icon type="plus" className="avatar-uploader-trigger"/>
                            }
                        </Upload>
                    )}
                </FormItem>


                <FormItem
                    {...formItemLayout}
                    label='启动页链接地址'
                    hasFeedback
                >
                    {getFieldDecorator('welcomeUrl', {
                        rules: [{ required: true, message: '请输入链接地址', whitespace: true }],
                        initialValue: detail.welcomeUrl
                    })(
                        <Input />
                    )}
                </FormItem>

                <FormItem
                    {...formItemLayout}
                    label='活动规则'
                    hasFeedback
                >
                    {getFieldDecorator('rule', {
                        rules: [{ required: true, message: '请输入活动规则', whitespace: true }],
                        initialValue: detail.rule
                    })(
                        <Input type="textarea" autosize="true" />
                    )}
                </FormItem>


                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit" size="large"
                            loading={this.state.buttonLoading}>{this.state.buttonLoading ? '正在提交...' : '提交'}</Button>
                </FormItem>
            </Form>

        </div>
      </div>
    )

  }
}
const Detail = Form.create()(BaseSettingDetail)
export default Detail